package com.leyou.user.interceptor;

import com.leyou.common.auth.pojo.AppInfo;
import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.constants.LyConstants;
import com.leyou.user.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * User: ycs
 * Date: 2020/9/2
 * Time: 19:50
 * Description: 自定义处理拦截器
 *
 * @author: ycs
 */
@Component
@Slf4j
@EnableConfigurationProperties(JwtProperties.class)
public class AppTokenInterceptor implements HandlerInterceptor {
    @Autowired(required = false)
    private JwtProperties jwtProp;

    /**
     * 拦截方法
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader(LyConstants.APP_TOKEN_HEADER);
        if (token == null) {
            //没有token
            return false;
        }
        Payload<AppInfo> payload;
        try {
            //解析token
            payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), AppInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
            //解析失败
            log.error("服务token解析失败");
            return false;
        }
        AppInfo appInfo = payload.getUserInfo();
        List<Long> targetList = appInfo.getTargetList();
        //没权限
        if (CollectionUtils.isEmpty(targetList) || !targetList.contains(jwtProp.getApp().getId())) {
            log.error("该服务token没有权限");
            return false;
        }
        return true;
    }
}
